#coding=utf-8
import datetime
today_isostr = datetime.date.today().isoformat()

from sqlalchemy.exceptions import InvalidRequestError
from stconfig import Session as sess
from stockdb.domains.tradeday import TradeDay
from stockdb.tables import tradedays
#from analyzer.tds import TdsAnalyzer

class FInstrucment(object):
    '''FInstrucment:Financial Instrucments 金融工具.'''
    def __init__(self, name):
        self.name = name
        
    def delete(self):
        
        sess.delete(self)
        sess.commit()
        sess.close()
    
    def find_td(self, date):
        try:
           return sess.query(TradeDay).filter_by(fins_id=self.fins_id, date=date).one()
        except InvalidRequestError:
           return None
           
    def tds_between(self, start, end=today_isostr):
        return sess.query(TradeDay).\
                    filter_by(fins_id=self.fins_id).\
                    filter('date>=:s and date<=:e').\
                    params(s=start, e=end).all()
                    
    def tds_since(self, start):
        return self.tds_between(start)
        
    def get_tdtoday(self):
        return self.find_td(today_isostr)
    today = property(fget=get_tdtoday)
    
    def get_latest_tradeday(self):
        r = sess.query(TradeDay).filter_by(fins_id=self.fins_id).order_by(tradedays.c.date.desc()).limit(1).all()
        if not r:return None
        return r[0]  
    latest_td = property(fget=get_latest_tradeday)
    
    '''
    def get_ta(self, start, end=today_isostr):
        tds = self.tds_between(start, end)
        if not tds:return None
        return TdsAnalyzer(tds)
    '''    
class SIndex(FInstrucment):
    pass
    
class Stock(FInstrucment):
    def __init__(self, name, code, market, ipo, iprice):
        self.name = name
        self.code = code
        self.market = market
        self.ipo = ipo
        self.iprice = iprice
        
    def get_ts(self, date=None):
        if not date:
            date = today_isostr
        for ts in self.tss:
            if date >= ts.date.isoformat():
                return ts.quantity                
    ts = property(fget=get_ts)
    
    def __repr__(self):
        return self.code
    
       
class Warrant(FInstrucment):
    pass
